<?php
abstract class My_DAO extends Zend_Db_Table_Abstract
{
	public function getTable()
	{
		return $this->_name;
	}
	
	private function getDTOClass()
	{
		$table = $this->getTable();
		$names = explode("_",$table);
		$className = "";
		foreach($names as $name)
		{
			$className .= ucfirst($name);
		}
		return $className."DTO";
	}

	public function loadData($id)
	{
		$result = $this->find($id);
		if (0 == count($result)) {
			return null;
		}
		$data = $result->current()->toArray();
		return $data;
	}

	public function load($id)
	{
		$data = $this->loadData($id);
		$dtoClass = $this->getDTOClass();
		$dto = new $dtoClass($data);
		return $dto;
	}

	public function loadAllData()
	{
		$resultSet = $this->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entries[] = $row->toArray();
		}
		return $entries;
	}

	public function loadAll()
	{
		$resultSet = $this->fetchAll();
		$entries   = array();
		$dtoClass = $this->getDTOClass();
		foreach ($resultSet as $row) {
			$entry = new $dtoClass($row->toArray());
			$entries[] = $entry;
		}
		return $entries;
	}
		
	public function buildQueryData($orderBy = "", $orderDirection="",
	$key = "", $field = "", $params = null)
	{
		return My_Db::buildQueryData($this->getTable(),$orderBy,$orderDirection,$key,$field);
	}
	
	public function save($dto)
    {
        $data = $dto->toArray();
        
        $table = $this->getTable();
    	$key = My_Db::getPrimaryKey($table);
        
        if (null == ($id = $dto->$key)) {
            $this->insert($data);
        } else {
            $this->update($data, array($key.' = ?' => $id));
        }
    }
    
    public function remove($id)
    {
    	$table = $this->getTable();
    	$key = My_Db::getPrimaryKey($table);
    	$where = $key.' = '.$id;
		return $this->delete($where);
    }
}